package com.ywqf_api.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ywqf_api.alipay.AlipayTradeAppPayModel;
import com.ywqf_api.base.BaseException;
import com.ywqf_api.dto.exc.ReturnExcution;
import com.ywqf_api.dto.in.*;
import com.ywqf_api.entity.Trade;
import com.ywqf_api.enums.ReturnEnum;
import com.ywqf_api.service.HouseKeepService;
import com.ywqf_api.service.MobileService;
import com.ywqf_api.utils.AlipayConfig;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.apache.ibatis.binding.MapperMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework
		.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;

@Controller
@RequestMapping("/pay")
public class PayController {
	@Autowired
	private MobileService mobileService;
	@Autowired
	private HouseKeepService houseKeepService;

	/**
	 * @param userId
	 *            充值人
	 * @param tradeMoney
	 *            充值money(RMB)
	 * @throws AlipayApiException
	 *             ModelAndView
	 */
	@RequestMapping(value = "createOrder", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public ReturnExcution alipay(@RequestParam("userId") String userId, @RequestParam("tradeMoney") String tradeMoney, @RequestParam("bodyString") String bodyString, @RequestParam("passback_params") String passback_params)
			throws AlipayApiException {

		String orderStr = "";

		//实例化客户端
		AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
		//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
		AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
		//SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)
		String bizContent = "{\"body\":\""+bodyString+"\","
				+"\"subject\": \""+bodyString+"\","
				+"\"out_trade_no\": \""+System.currentTimeMillis()+"\","
				+"\"timeout_express\": \"30m\","
				+"\"total_amount\": \"0.01\","
				+"\"product_code\":\"QUICK_MSECURITY_PAY\","
				+"\"passback_params\":\""+passback_params+"\""
				+"}";
		request.setBizContent(bizContent);
		request.setNotifyUrl(AlipayConfig.notify_url);
		try {
			//这里和普通的接口调用不同，使用的是sdkExecute
			AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
			System.out.println(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
			return new ReturnExcution(ReturnEnum.ALIPAY_CREAT_SUCCESS,response.getBody());

		} catch (AlipayApiException e) {
			e.printStackTrace();
			return new ReturnExcution(ReturnEnum.ALIPAY_CREAT_FAIL,orderStr);
		}



	}

	/**
	 * 支付宝支付成功后.回调该接口
	 *
	 * @param request
	 * @return
	 * @throws IOException
	 */

	@RequestMapping(value = "notify_url", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	@Transactional
	public String notify(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//获取支付宝POST过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		//切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
		//boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
		boolean flag = false;
		try {
			flag = AlipaySignature.rsaCheckV1(params,AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.CHARSET,AlipayConfig.SIGNTYPE);
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}

		if (flag == true){
			String paramsString = params.get("passback_params");
			String thirdNo = params.get("out_trade_no");
			String status = params.get("trade_status");
			if (status.equals("TRADE_SUCCESS")){
				String decodeString = URLDecoder.decode(paramsString, "utf-8");
//			String name = jsStr.getString("name");
				System.out.println(decodeString);
//			JSONObject jsStr = JSONObject.fromObject(paramsString);
				Map<String,String> json = (Map<String,String>) JSONObject.fromObject(decodeString);
				System.out.println(json);
				String types = json.get("type");
				int type = Integer.parseInt(types);
				String orderIdString = json.get("orderId");
				int orderId = Integer.parseInt(orderIdString);
				if(type == 0){ //物业
					int success = mobileService.updateOrderStatus(orderId,thirdNo);
					if(success > 0){
						EstateFeeDto estateFeeDto = new EstateFeeDto();
						String houseID = json.get("houseId");
						estateFeeDto.setHouseId(Integer.parseInt(houseID));
						String ownerName = json.get("ownerName");
						estateFeeDto.setOwnerName(ownerName);
						String area = json.get("area");
						estateFeeDto.setArea(Double.parseDouble(area));
						String estateUnitPrice = json.get("estateUnitPrice");
						estateFeeDto.setEstateUnitPrice(Double.parseDouble(estateUnitPrice));
						String payMonth = json.get("payMonth");
						estateFeeDto.setPayMonth(Integer.parseInt(payMonth));
						String payDate = json.get("payDate");
						estateFeeDto.setPayDate(payDate);
						String paymentAmount = json.get("paymentAmount");
						estateFeeDto.setPaymentAmount(Double.parseDouble(paymentAmount));
						String estateDiscountTypeId = json.get("estateDiscountTypeId");
						estateFeeDto.setEstateDiscountTypeId(Integer.parseInt(estateDiscountTypeId));
						String serviceStartDate = json.get("serviceStartDate");
						String serviceEndDate = json.get("serviceEndDate");
						estateFeeDto.setServiceStartDate(serviceStartDate);
						estateFeeDto.setServiceEndDate(serviceEndDate);
						String payType = json.get("payType");
						estateFeeDto.setPayType(Integer.parseInt(payType));
						String customerId = json.get("customerId");
						estateFeeDto.setCustomerId(Integer.parseInt(customerId));
						int save = mobileService.saveEstateFees(estateFeeDto);
						if(save > 0){
							return "成功";
						}else{
							throw new BaseException("失败");
						}
					}else{
						throw new BaseException("失败");
					}
				}else if(type == 1){    //车位
					int success = mobileService.updateOrderStatus(orderId,thirdNo);
					if(success > 0){
						ParkingFeeDto parkingFeeDto = new ParkingFeeDto();
						String parkingSpaceId = json.get("parkingSpaceId");
						parkingFeeDto.setParkingSpaceId(Integer.parseInt(parkingSpaceId));
						String parkingUnitPrice = json.get("parkingUnitPrice");
						parkingFeeDto.setParkingUnitPrice(Double.parseDouble(parkingUnitPrice));
						String payMonth = json.get("payMonth");
						parkingFeeDto.setPayMonth(Integer.parseInt(payMonth));
						String carOwner = json.get("carOwner");
						parkingFeeDto.setCarOwner(carOwner);
						String serviceStartDate = json.get("serviceStartDate");
						String serviceEndDate = json.get("serviceEndDate");
						parkingFeeDto.setServiceStartDate(serviceStartDate);
						parkingFeeDto.setServiceEndDate(serviceEndDate);
						String payDate = json.get("payDate");
						parkingFeeDto.setPayDate(payDate);
						String paymentAmount = json.get("paymentAmount");
						parkingFeeDto.setPaymentAmount(Double.parseDouble(paymentAmount));
						String parkingDiscountTypeId = json.get("parkingDiscountTypeId");
						parkingFeeDto.setParkingDiscountTypeId(Integer.parseInt(parkingDiscountTypeId));
						String payType = json.get("payType");
						parkingFeeDto.setPayType(Integer.parseInt(payType));
						String customerId = json.get("customerId");
						parkingFeeDto.setCustomerId(Integer.parseInt(customerId));
						int save = mobileService.saveParkingFees(parkingFeeDto);
						if(save > 0){
							return "成功";
						}else{
							throw new BaseException("失败");
						}
					}else{
						throw new BaseException("失败");
					}
				}else if(type == 2){   //采暖
					int success = mobileService.updateOrderStatus(orderId,thirdNo);
					if(success > 0){
						HeatingFeeDto heatingFeeDto = new HeatingFeeDto() ;
						heatingFeeDto.setOrderId(orderId);
						String houseID = json.get("houseId");
						heatingFeeDto.setHouseId(Integer.parseInt(houseID));
						String ownerName = json.get("ownerName");
						heatingFeeDto.setOwnerName(ownerName);
						String payType = json.get("payType");
						heatingFeeDto.setPayType(Integer.parseInt(payType));
						String year = json.get("year");
						heatingFeeDto.setYear(Integer.parseInt(year));
						String heatingDiscount = json.get("heatingDiscount");
						heatingFeeDto.setHeatingDiscount(Double.parseDouble(heatingDiscount));
						String paymentDate = json.get("paymentDate");
						heatingFeeDto.setPaymentDate(paymentDate);
						String paymentAmount = json.get("paymentAmount");
						heatingFeeDto.setPaymentAmount(Double.parseDouble(paymentAmount));
						String heatingArea = json.get("heatingArea");
						heatingFeeDto.setHeatingArea(Double.parseDouble(heatingArea));
						String discountHeatingUnitPrice = json.get("discountHeatingUnitPrice");
						heatingFeeDto.setDiscountHeatingUnitPrice(Double.parseDouble(discountHeatingUnitPrice));
						int save = mobileService.saveHeatingFees(heatingFeeDto);
						if(save > 0){
							return "成功";
						}else{
							throw new BaseException("失败");
						}
					}else{
						throw new BaseException("失败");
					}
				}else if(type == 3){   //水费
					int success = mobileService.updateOrderStatus(orderId,thirdNo);
					if(success > 0){
						WaterFeeDto waterFeeDto = new WaterFeeDto() ;
						waterFeeDto.setOrderId(orderId);
						String houseID = json.get("houseId");
						waterFeeDto.setHouseId(Integer.parseInt(houseID));
						String waterRate = json.get("waterRate");
						waterFeeDto.setWaterRate(Double.parseDouble(waterRate));
						String payTons = json.get("payTons");
						waterFeeDto.setPayTons(Integer.parseInt(payTons));
						String unitPrice = json.get("unitPrice");
						waterFeeDto.setUnitPrice(Double.parseDouble(unitPrice));
						int save = mobileService.saveWaterFees(waterFeeDto);
						if(save > 0){
							return "成功";
						}else{
							throw new BaseException("失败");
						}
					}else{
						throw new BaseException("失败");
					}
				}else if(type == 4){        //电费
					int success = mobileService.updateOrderStatus(orderId,thirdNo);
					if(success > 0){
						ElectricityFeeDto electricityFeeDto = new ElectricityFeeDto() ;
						electricityFeeDto.setOrderId(orderId);
						String houseID = json.get("houseId");
						electricityFeeDto.setHouseId(Integer.parseInt(houseID));
						String electricityRate = json.get("electricityRate");
						electricityFeeDto.setElectricityRate(Double.parseDouble(electricityRate));
						int save = mobileService.saveElectricityFees(electricityFeeDto);
						if(save > 0){
							return "成功";
						}else{
							throw new BaseException("失败");
						}
					}else{
						throw new BaseException("失败");
					}
				}else if(type == 5){
					int success = mobileService.updateOrderStatus(orderId,thirdNo);
					if(success > 0){
						HouseKeepDto houseKeepDto = new HouseKeepDto() ;
						houseKeepDto.setOrderId(orderId);
						String goodsId = json.get("goodsId");
						houseKeepDto.setGoodsId(Integer.parseInt(goodsId));
						String customerId = json.get("customerId");
						houseKeepDto.setCustomerId(Integer.parseInt(customerId));
						int save = houseKeepService.saveHouseKeepCard(houseKeepDto);
						if(save > 0){
							return "成功";
						}else{
							throw new BaseException("失败");
						}
					}else{
						throw new BaseException("失败");
					}
				}
			}

		}else {

		}

		return "";
	}

	/**
	 * 支付宝支付成功后.通知页面
	 *
	 * @author Zhao
	 * @date 2017年11月2日
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	/*
	 * @RequestMapping(value="api/alipay/return_url",method={RequestMethod.POST,
	 * RequestMethod.GET})
	 *
	 * @ResponseBody public Model returnUrl(@RequestParam("id") String
	 * id,HttpServletRequest request,Model model) throws
	 * UnsupportedEncodingException { System.err.println("。。。。。。 同步通知 。。。。。。");
	 * System.err.println("。。。。。。 同步通知 。。。。。。"); System.err.println(
	 * "。。。。。。 同步通知 。。。。。。"); Map returnMap = new HashMap(); try {
	 *
	 * Trade trade = tradeService.selectByOrderNumber(id); // 返回值Map if(trade
	 * !=null && trade.getTradeStatus() == 2){ User user =
	 * userService.selectByPrimaryKey(trade.gettUserId());
	 * returnMap.put("tradeType", trade.getTradeType()); //支付方式
	 * returnMap.put("phoneNum", user.getPhoneNumber()); //支付帐号
	 * returnMap.put("tradeMoney", trade.getTradeMoney()+""); //订单金额
	 *
	 * }else{ model.addAttribute("msg", "查询失败"); model.addAttribute("status",
	 * 0); } model.addAttribute("returnMap", returnMap);
	 * System.err.println(returnMap); model.addAttribute("msg", "查询成功");
	 * model.addAttribute("status", 0); } catch (Exception e) {
	 * model.addAttribute("msg", "查询失败"); model.addAttribute("status", 1); }
	 *
	 * return model; }
	 */
}
